//
//  OnlineStatementView.swift
//  GreenDeal
//
//  Created by Moennig Q on 9/1/2023.
//

import UIKit
import WebKit
class OnlineStatementView: GreenNaviBarView  {
    var webView: WKWebView!
    let withoutNetworkView = DatalLoadFaildView()
    var progBar :UIProgressView!
    
    func initWebView(vc: OnlineStatementViewController){
        self.backgroundColor = .white
        let userContent = WKUserContentController()
        let config = WKWebViewConfiguration()
        config.userContentController = userContent
        let weakDelegate = WeakScriptMessageDelegate(vc)//释放WKScriptMessageHandler对self的强引用，防止引用循环导致内存泄漏
        if APPConfig.isTestFlag {
            config.userContentController.add(weakDelegate, name: WebViewConvention.logger.rawValue)//打印JS中的console.log(信息)
        }
        config.userContentController.add(weakDelegate, name: WebViewConvention.event.rawValue)//和Web约定的参数,中间的直接用event，里边都有一个event参数
        config.userContentController.add(weakDelegate, name: WebViewConvention.webViewEvent.rawValue)//和Web约定的参数，最后的提交用这个
        self.webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), configuration: config)
        self.webView.navigationDelegate = vc
        self.webView.uiDelegate = vc
        self.webView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        self.addSubview(webView)
        webView.snp.makeConstraints { (make) in
            make.top.equalTo(self.topBackView.snp.bottom).offset(-20)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(self.safeAreaLayoutGuide.snp.bottom)
        }
        //process bar
        progBar = UIProgressView()
        progBar.progress = 0.0
        progBar.tintColor = UIColor(rgb: 0x3BADFF)
        progBar.backgroundColor = .white
        self.webView.addSubview(progBar)
        progBar.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(3)
        }
        //协议加载失败的试图
        self.withoutNetworkView.isHidden = true
        self.addSubview(withoutNetworkView)
        withoutNetworkView.snp.makeConstraints { (make) in
            make.top.equalTo(self.safeAreaLayoutGuide.snp.top)
            make.left.right.bottom.equalToSuperview()
        }
        //add observer
        self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
    }
    func showViewAfterLoad(_ loadSuccessFlag: Bool){
        if loadSuccessFlag {
            self.webView.isHidden = false
            self.withoutNetworkView.isHidden = true
            self.bringSubviewToFront(self.webView)
        }else{
            self.webView.isHidden = true
            self.withoutNetworkView.isHidden = false
            self.bringSubviewToFront(self.withoutNetworkView)
            
        }
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progBar.alpha = 1.0
            self.progBar.setProgress(Float(webView.estimatedProgress), animated: true)
            //Max value of process bar is 1.0
            if(self.webView.estimatedProgress >= 1.0) {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: UIView.AnimationOptions.curveEaseInOut, animations: { () -> Void in
                    self.progBar.alpha = 0.0
                }, completion: { (finished:Bool) -> Void in
                    self.progBar.progress = 0
                })
            }
        }
    }
    deinit{
        DebugLog("释放\(self)")
        self.webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }
}
